package com.suxin.test.netty.adv.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.adv.vo.Message;
import org.example.netty.adv.vo.MessageType;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/21 10:48
 */
@Slf4j
public class ClientHeartbeatBoundChannel extends SimpleChannelInboundHandler<Message> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        byte type = msg.getMessageHeader().getType();
        if (MessageType.HEARTBEAT_RESP.value() == type) {
            log.info("client 处理心跳 {}",msg);
        }else {
            // 投递给下一个链条
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            // 写空闲触发
            if (IdleStateEvent.WRITER_IDLE_STATE_EVENT == event) {
                Message message = Message.buildClientHeartBeat();
                ctx.writeAndFlush(message);
            }
        }

        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
